package io.alexkozlov.jpointfeddiscovery;

import io.alexkozlov.jpointfeddiscovery.models.ServiceExport;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Getter
@Service
public class StorageController {
    private static final Logger LOGGER = LoggerFactory.getLogger(StorageController.class);
    private final ArrayList<ServiceExport> exports = new ArrayList<>();

    public boolean addExport(ServiceExport export) {
        boolean result = true;

        for (ServiceExport ex : exports) {
            if (ex.spec.name.equals(export.spec.name) && ex.spec.namespace.equals(export.spec.namespace)) {
                result = false;
                break;
            }
        }

        if (result) {
            LOGGER.info("Export with name " + export.spec.name + " and namespace " + export.spec.namespace + " and cluster name " + export.spec.clusterName + " added");
            exports.add(export);
        } else {
            LOGGER.error("Export with name " + export.spec.name + " and namespace " + export.spec.namespace + " and cluster name " + export.spec.clusterName +" already exists");
        }

        return result;
    }

    public ArrayList<ServiceExport> getExport(String name) {
        ArrayList<ServiceExport> result = new ArrayList<>();

        for (ServiceExport ex : exports) {
            if (ex.spec.name.equals(name)) {
                result.add(ex);
            }
        }

        return result;
    }

    public Boolean removeExport(ServiceExport serviceExport) {
        boolean result;
        result = exports.remove(serviceExport);
        if (result) {
            LOGGER.info("Export with name " + serviceExport.spec.name + " and namespace " + serviceExport.spec.namespace + " and cluster name " + serviceExport.spec.clusterName +" removed");
        }
        return result;
    }
}
